package com.engr.lyx.blog.biz.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.engr.lyx.blog.biz.enums.StatusEnum;
import com.engr.lyx.blog.biz.repository.comment.CommentRepository;
import com.engr.lyx.blog.biz.service.CommentService;
import com.engr.lyx.blog.client.entity.Comment;
import com.engr.lyx.blog.client.req.CommentReq;
import com.engr.lyx.blog.client.vo.CommentVO;
import com.engr.lyx.common.utils.BeanUtils;
import com.engr.lyx.common.utils.TreeUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * @program blog
 * @description:
 * @author: LiuYanXin
 * @create: 2020-12-21 22:08
 */
@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentRepository commentRepository;

    @Override
    public Comment saveComment(CommentReq req) {

        Comment comment = BeanUtils.copy(req, Comment.class);
        comment.setCreateTime(new Date());
        comment.setUpdateTime(new Date());
        comment.setStatus(StatusEnum.EFFECTIVE.getCode());
        return commentRepository.save(comment);
    }

    @Override
    public List<CommentVO> queryTreeByArticleId(String articleId) {

        List<Comment> list = commentRepository.findByArticleId(NumberUtils.toLong(articleId));
        if (CollUtil.isEmpty(list)) {
            return Collections.emptyList();
        }
        List<CommentVO> data = BeanUtils.copyList(list, CommentVO.class);
        return TreeUtils.buildByRecursive(data, "0");
    }
}
